const log4js = require('log4js');

// 配置 log4js
log4js.configure({
  appenders: {
    console: { type: 'console' }, // 控制台输出
    file: { // 日志文件输出
      type: 'file',
      filename: 'logs/access.log',
      maxLogSize: 10485760, // 10MB
      backups: 5, // 最多保留5个备份
      compress: true, // 压缩备份文件
    },
    errorFile: { // 错误日志单独记录
      type: 'file',
      filename: 'logs/errors.log',
      compress: true,
    },
  },
  categories: {
    default: { appenders: ['console', 'file'], level: 'info' }, // 默认分类
    error: { appenders: ['console', 'errorFile'], level: 'error' }, // 错误分类
  },
});

const logger = log4js.getLogger();
const errorLogger = log4js.getLogger('error');

// 日志输出中间件
const logsOutPutMiddleWare = (req, res, next) => {
  const startTime = Date.now(); // 请求开始时间
  res.on('finish', () => { // 在响应结束时记录日志
    const endTime = Date.now(); // 请求结束时间
    const duration = endTime - startTime; // 请求耗时
    // 日志内容
    const logMessage = `[${new Date().toISOString()}] ${req.method} ${req.originalUrl} - ${res.statusCode} (${duration}ms)`;

    // 根据响应状态码记录不同日志级别
    if (res.statusCode >= 500) {
      logger.error(logMessage);
    } else if (res.statusCode >= 400) {
      logger.warn(logMessage);
    } else {
      logger.info(logMessage);
    }
  });

  // 捕获错误信息
  process.on('uncaughtException', (err) => {
    const errorDetails = `Error: ${err.message}\nStack Trace: ${err.stack}`;
    errorLogger.error(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl}\n${errorDetails}`);
  });

  process.on('unhandledRejection', (reason, promise) => {
    const rejectionDetails = `Unhandled Rejection at: ${promise}\nReason: ${reason}`;
    errorLogger.error(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl}\n${rejectionDetails}`);
  });
  next(); // 继续处理请求
};

module.exports = logsOutPutMiddleWare;
